package com.firefly.service.command.ums;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.firefly.dao.dao.ums.po.*;
import com.firefly.dao.dao.ums.service.*;
import com.firefly.util.handle.FireflyException;
import com.firefly.dao.dto.ums.AdminLoginDto;
import com.firefly.dao.vo.ums.LoginVo;
import com.firefly.service.repository.ums.AdminRepository;
import com.firefly.util.utils.CryptUtils;
import com.firefly.util.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @description: 管理员登录
 * @author: lzg(萤火科技 ： 854378082 @ qq.com)
 * @date: 2022/12/9
 **/
@Service
public class LoginCommand {
   private final AdminService adminService;
   private final RoleAdminService roleAdminService;
   private final DepartmentAdminService departmentAdminService;
   private final RolePermissionService rolePermissionService;
   private final AdminRepository adminRepository;
   private final MenuService menuService;
   private final CacheManager cacheManager;
   @Autowired
   public LoginCommand(AdminService adminService, RoleAdminService roleAdminService, DepartmentAdminService departmentAdminService, RolePermissionService rolePermissionService, AdminRepository adminRepository, MenuService menuService,CacheManager cacheManager){
      this.adminService = adminService;
      this.roleAdminService = roleAdminService;
      this.departmentAdminService = departmentAdminService;
      this.rolePermissionService = rolePermissionService;
      this.adminRepository = adminRepository;
      this.menuService = menuService;
      this.cacheManager = cacheManager;
   }

    public Object postLogin(AdminLoginDto request,String requestIp) throws Exception {
        QueryWrapper<AdminPo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", request.getName()).eq("del_flag", 0);
        AdminPo detail = adminService.getOne(queryWrapper);
        if (detail == null) {
            throw new FireflyException(403, "没有找到此用户");
        }
        // 密码判断
        String passwd = CryptUtils.encryptToMD5(CryptUtils.encryptToMD5(request.getPassword() + "." + detail.getCrypt() + "." + request.getPassword()));
        if (!passwd.equals(detail.getPassword())) {
            throw new FireflyException(403, "密码不正确");
        }
        if (detail.getStatus() != 1) {
            throw new FireflyException(403, "用户被禁用");
        }
        // 找所有角色，菜单权限，所属部门
        QueryWrapper<RoleAdminPo> queryRoleAdmin = new QueryWrapper<>();
        queryRoleAdmin.eq("admin_id", detail.getId()).select("role_id");
        List<Object> roleIds = roleAdminService.listObjs(queryRoleAdmin);
        List<Object> urls = null;
        if (!detail.getId().equals(1)){
            if (roleIds.size() <= 0){
                throw new FireflyException(403, "用户还没有分配角色，请先联系管理员");
            }else{
                QueryWrapper<RolePermissionPo> queryRolePermission = new QueryWrapper<>();
                queryRolePermission.in("role_id", roleIds).select("url");
                urls = rolePermissionService.listObjs(queryRolePermission);
            }
        }else {
            QueryWrapper<MenuPo> queryMenu = new QueryWrapper<>();
            queryMenu.select("url");
            urls = menuService.listObjs(queryMenu);
        }
        QueryWrapper<DepartmentAdminPo> queryDepartmentAdmin = new QueryWrapper<>();
        queryDepartmentAdmin.eq("admin_id", detail.getId());
        List<Object> departmentIds = departmentAdminService.listObjs(queryDepartmentAdmin);
        // 更新ip，登录时间
        adminRepository.updateLastIpAndTime(detail.getId(), requestIp, LocalDateTime.now());
        // 生成token
        String username = (detail.getId()).toString();
        String token = JWTUtil.sign(username, 25, "c-token");
        LoginVo result = new LoginVo();
        result.setId(detail.getId());
        result.setName(detail.getName());
        result.setPhone(detail.getPhone());
        result.setToken(token);
        result.setRoleIds(roleIds);
        result.setDepartmentIds(departmentIds);
        result.setUrls(urls);
        // 开始存redis
        Cache tokenCache = cacheManager.getCache("c-token");
        tokenCache.evict(username);
        tokenCache.put(username, result);
        return result;
    }
}
